<?php
/**
 * StatsController 
 *
 */
 
 require_once APPLICATION_PATH . '/models/Reading.php';
 
class StatsController extends Zend_Controller_Action 
{
    protected $model;
 
    protected function _getModel()
    {
        if (null === $this->model) {
            require_once APPLICATION_PATH . '/models/Room.php';
            $this->model = new Model_Room();
        }
        return $this->model;
    }    

    protected function _getSettingModel() 
    {
      if (null === $this->setting) {
          require_once APPLICATION_PATH . '/models/Setting.php';
          $this->setting = new Model_Setting();
      }
      return $this->setting;
    }
     
     
    protected function scaleReading($reading, $scale) {
      if ($scale == "C") {
        return Model_Reading::toCelsius($reading);
      }
      return $reading;
    }

    /**
     * The "index" action is the default action for all controllers. This 
     * will be the landing page of your application.
     *
     * Assuming the default route and default router, this action is dispatched 
     * via the following urls:
     *   /
     *   /index/
     *   /index/index
     *
     * @return void
     */
    public function indexAction() 
    {
        $model    = $this->_getModel();
        $rooms    = $model->fetchReadings(); 
        $setting  = $this->_getSettingModel();        

        $scale    = ($setting->isCelsius() == true) ?  "C"    : "F";
        for ($i=0; $i < count($rooms); $i++) {
          // find room stats
          $sum = 0;
          $min =  9999999;
          $max = -9999999;
          for($j=0; $j < count($rooms[$i]['readings']); $j++) {
            $reading = $rooms[$i]['readings'][$j]['reading'];
            $reading = $this->scaleReading($reading, $scale);
            // set readings based on time for graph
            // e.g. "October 12, 1988 13:14:00" for JS Date()
            // avg reading per min
            $date = date('F j, Y  G:i:0', strtotime($rooms[$i]['readings'][$j]['created']));
            $readings[$date][$i][] = $reading;
            
            if ($reading < $min) { $min = $reading; }
            if ($reading > $max) { $max = $reading; }
            $sum += $reading;
            $rooms[$i]['readings'][$j]['reading'] = round($reading, Model_Reading::getPrecision()); 
          }
          if ($min == 9999999) {
            $rooms[$i]['min']   = 0;
            $rooms[$i]['max']   = 0;
            $rooms[$i]['range'] = 0;
          } else {
            $rooms[$i]['min']   = round($min, Model_Reading::getPrecision());
            $rooms[$i]['max']   = round($max, Model_Reading::getPrecision());
            $rooms[$i]['range'] = round(($max-$min), Model_Reading::getPrecision());
          }
          $n = count($rooms[$i]["readings"]);
          if ($n == 0) {
            $rooms[$i]["average"] = 0;
            $rooms[$i]["stddev"]  = 0;            
          } else {
            $mean = $sum/$n;
            // find std dev
            $ss = 0.0;
            foreach ($rooms[$i]["readings"] as $reading) { // find sum 
              $ss += pow(($reading['reading'] - $mean),2); 
            }
            $rooms[$i]["average"] = round($mean, Model_Reading::getPrecision());
            $rooms[$i]["stddev"]  = round(sqrt($ss/$n), Model_Reading::getPrecision()); 
          }
        }
        // average readings for timeline 
        foreach($readings as $key=>$value) {
          for($j=0; $j < count($value); $j++) {
            $nn = count($value[$j]);
            $summ = 0;
            for($k=0; $k < $nn; $k++) { 
              $summ += $value[$j][$k];
            }
            if ( $nn > 0 )  {
              $readings_avg[$key][$j] = round($summ/$nn, Model_Reading::getPrecision());
            } else {
              $readings_avg[$key][$j] = 0;
            }
          }
        }

        $this->view->nav      = "stats";
        $this->view->mode     = ($setting->isHeat()    == true) ?  "heat" : "cool";
        $this->view->scale    = $scale;
        $this->view->readings = $readings_avg;

        if ($scale == "C") {
            for ($i=0; $i < count($rooms); $i++) {
              $rooms[$i]['setpoint'] = round($this->scaleReading($rooms[$i]['setpoint'], $scale), Model_Reading::getPrecision());
            }
        }
        
        $this->view->rooms = $rooms;
        
        //print_r($readings_avg);
        //exit;
    }

}
